<template>
	<headerNavbarVue title='确认订购'></headerNavbarVue>
	<view class="body">
		<view class="benefits">
			<benefitsCardVue :titleInfo="right_interest"></benefitsCardVue>
		</view>
		<view class="cover-image">
			<image :src="imageUrl +  coverImage" mode="widthFix"></image>
		</view>
		<view class="prcie">
			<priceBreakdownVue :orderinfo="orderinfo" :RoomCount="currentRoomCount" :roomValue="currentroomValue"
				:singleDifferenceRate="currentSingleDifferenceRate" @finalPriceChange="handleFinalPriceChange">
			</priceBreakdownVue>
		</view>
		<view class="Contact">
			<contactFormVue :peopleNumber="peopleNumber" :orderinfo="orderinfo" :addPersonInfo="addPersonInfo"
				:idInfo="AllTravelersRes" @roomCountChange="handleRoomCountChange" @roomValue="handleroomValue"
				@submitForm="handleSubmitForm" :singleDifferenceRate="currentSingleDifferenceRate">
			</contactFormVue>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import { imageUrl } from '../../config/request/request';
	import headerNavbarVue from '@/components/headerNavbar.vue'
	import benefitsCardVue from '@/homeSubpages/ProductDetails/components/benefitsCard.vue';
	import priceBreakdownVue from './components/priceBreakdown.vue';
	import contactFormVue from './components/contactForm.vue';
	import {
		ref
	} from 'vue';
	import {
		GetAllTravelers,
		GetTravelers
	} from '../../config/API/Travelers';
	import {
		CreateOrder,
		wechatPay
	} from '@/config/API/ProductDetails.js'
	const userId = ref(0)
	//套餐名
	const order_detail = ref('')
	const openid = ref('')
	//起止日期
	const starTime = ref('')
	//封面图片
	const coverImage = ref('')
	//权益
	const right_interest = ref()
	//人数
	const peopleNumber = ref(1)
	//接收上个页面的数据
	const orderinfo = ref({})
	const addPersonInfo = ref()
	//所有出行人信息
	const AllTravelersRes = ref()
	// 房间数量
	const currentRoomCount = ref()
	//房型内的所有数据
	const currentroomValue = ref()
	//单房差价
	const currentSingleDifferenceRate = ref(0)
	//最终价格
	const totalPrice = ref(0)
	//最终房间差价
	const allDifferenceRate = ref(0)
	onLoad(async (e) => {
		if (uni.getStorageSync('userInfo').id) {
			userId.value = uni.getStorageSync('userInfo').id
			openid.value = uni.getStorageSync('userInfo').openID
			console.log('1778058383917780583839', userId.value);
		} else {
			console.log('未登录');
		}
		console.log('传参', e);
		console.log('获取旅游人数：', e.peoples);
		coverImage.value = e.coverImage
		peopleNumber.value = e.peoples
		order_detail.value = e.order_detail
		right_interest.value = JSON.parse(e.right_interest)
		const startdate = e.startToEnd.split('-')[0]
		const formattedStartDate = startdate.split('.').map((part, index) => {
			return index > 0 && part.length === 1 ? '0' + part : part;

		}).join('-')
		starTime.value = formattedStartDate
		orderinfo.value = e
		currentSingleDifferenceRate.value = Number(e.type_price_difference)
		console.log('currentSingleDifferenceRate', currentSingleDifferenceRate.value);
		console.log('orderinfo', orderinfo.value);
		const getAllTravelersRes = await getAllTravelers()
		AllTravelersRes.value = getAllTravelersRes
		console.log('getAllTravelersRes', AllTravelersRes.value);
	})
	onShow(async () => {
		const getAllTravelersRes = await getAllTravelers()
		AllTravelersRes.value = getAllTravelersRes
	});
	//获取这个账户在的所有出行人的信息
	const getAllTravelers = async () => {
		const res = await GetAllTravelers(uni.getStorageSync('userInfo').id)
		console.log('res', res);
		if (res.code == 200) {
			return res.data
		} else {
			uni.showToast({
				title: '网络错误',
				icon: 'none'
			})
		}

	}
	//创建订单的请求
	const OrderPost = async (itform) => {
		return await CreateOrder(itform)
	}
	//接收子组件监听的房间数量
	const handleRoomCountChange = (newRoomCount) => {
		currentRoomCount.value = newRoomCount
	}
	//接收子组件监听房型的数据
	const handleroomValue = (newroomValue) => {
		currentroomValue.value = newroomValue
	}
	//接收最终房价
	const handleFinalPriceChange = (finalPrice, DifferenceRate) => {
		totalPrice.value = finalPrice
		allDifferenceRate.value = DifferenceRate
		console.log('totalPrice.value', totalPrice.value);
	}
	//最终点击预定按钮
	const handleSubmitForm = async (resultCode, orderForm, rooms) => {
		console.log('rooms============>', rooms);
		if (resultCode === 1) {
			uni.showLoading({
				title: '支付中',
				mask: 'true'
			})
			const travelersList = rooms.map(room => room.selectedItems).flat().map(item => ({
				travelers_id: item.travelers_id,
				travelers_name: item.travelers_name,
				travelers_card_number: item.travelers_card_number,
				travelers_phone: item.travelers_phone,
			}))
			console.log('travelersList', JSON.stringify(travelersList));
			let form = {
				wechat_user_id: userId.value,
				order_shop_type: 1,
				order_detail: order_detail.value,
				order_username: orderForm.Name,
				order_phone: orderForm.phoneNumber,
				travel_number: Number(peopleNumber.value),
				buy_count: null,
				all_cost: totalPrice.value,
				order_difference_rate: Number(allDifferenceRate.value), //TODO房差费
				// all_cost: 2,
				hotel_number: currentRoomCount.value,
				travel_date: starTime.value,
				order_shop_id: Number(orderinfo.value.shop_id),
				order_shop_cost_id: Number(orderinfo.value.shop_cost_id),
				order_cost_date_id: Number(orderinfo.value.shop_data_id),
				order_traveler_list: JSON.stringify(travelersList)
			}
			console.log('form', form);
			try {
				const orderRes = await OrderPost(form)
				if (orderRes.code == 200) {
					const payForm = {
						openid: openid.value,
						order_id: orderRes.data.order_id
					}
					try {
						const payRes = await wechatPay(payForm)
						if (payRes.code == 200) {
							// wxPay(payRes.data)
							uni.requestPayment({
								provider: "wxpay",
								...payRes.data,
								success: async (res) => {
									console.log(res);

									uni.hideLoading();
									uni.showToast({
										title: '支付成功',
										icon: 'success',
										duration: 1000
									});
									// 延迟后再跳转
									setTimeout(() => {
										uni.redirectTo({
											url: `/homeSubpages/PublicTipsPage/PaySucces?orderId=${payForm.order_id}`
										});
									}, 1000);
								},
								fail: (err) => {
									console.log(err);
									// 支付失败后的操作
									// 例如，提示用户支付失败

									uni.showToast({
										title: '支付已取消',
										icon: 'error',
										duration: 1000
									});
									uni.hideLoading();
									setTimeout(() => {
										uni.redirectTo({
											url: `/myselfSubpages/order/hotelOrderDetails/hotelOrderDetails?orderId=${payForm.order_id}`
										});
									}, 1000);
									// 隐藏加载提示
								},
							});
						} else if (payRes.code == 0) {
							uni.showToast({
								title: payRes.msg + '还有' + payRes.data + '张票',
								icon: 'none',
								duration:2500
							})
							// 隐藏加载提示
							uni.hideLoading();

						} else {
							uni.showToast({
								title: '订单异常',
								icon: 'none'
							})
							// 隐藏加载提示
							uni.hideLoading();
						}
						console.log('payRes', payRes.data);
						// console.log('成功预定');
					} catch (e) {
						//TODO handle the exception
						uni.showToast({
							title: e,
							icon: 'none'
						})
						// 隐藏加载提示
						uni.hideLoading();
						console.log('支付错误', e);
					}

				} else {
					uni.showToast({
						title: '支付失败，请重试',
						icon: 'error'
					})
					uni.hideLoading();
				}
			} catch (e) {
				uni.hideLoading();
				//TODO handle the exception
				uni.showToast({
					title: e,
					icon: 'none'
				})
			}

		}
	}
</script>

<style>
	.body {
		width: 100%;
		/* background-color: rgba(242, 242, 242, 1); */
		background-color: #f5f6f7;
		padding: 10rpx 0 200rpx 0;
		box-sizing: border-box;
	}

	.cover-image {
		margin: 20rpx auto;
		background: rgba(247, 247, 247, 1);
		width: 90%;
	}

	.cover-image image {
		width: 676rpx;
		height: 314rpx;
		border-radius: 20rpx;
	}
</style>